package com.henry.base.concurrency;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestBarrier {
    private static final int threadNum=3;
    static long begin;
    static CyclicBarrier cyclic = new CyclicBarrier(threadNum,()->{
        long end = System.nanoTime();

        System.out.println("花费时间："+(end-begin)/1000/1000+"ms");
    });

    public static class Sub implements Runnable {

        @Override
        public void run() {
//            cyclic.reset();
            try {
                Thread.sleep(new Random().nextInt(5)*1000);
                System.out.println("......");
                cyclic.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(threadNum);
        begin=System.nanoTime();
        for (int i = 0; i < threadNum; i++) {
            pool.submit(new Sub());
        }

        System.out.println("xasfafasf");
        pool.shutdown();
    }

}
